import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // 默认使用localStorage
import componentsReducer, { ComponentsStateType } from "./componentsReducer";
import userInfoReducer, { UserInfoStateType } from "./userInfoReducer";
import pageInfoReducer, { PageInfoStateType } from "./pageInfoReducer";
import undoable, { excludeAction, StateWithHistory } from "redux-undo";

export type StateType = {
  userInfo: UserInfoStateType;
  components: StateWithHistory<ComponentsStateType>;
  pageInfo: PageInfoStateType;
};

export const PERSIST_KEY = "root";

// redux-persist配置
const persistConfig = {
  key: PERSIST_KEY,
  storage,
};

const C_PREFIX = "components/";

export const store = configureStore({
  reducer: persistReducer(
    persistConfig,
    // 合并reducer
    combineReducers({
      userInfo: userInfoReducer,
      components: undoable(componentsReducer, {
        // 历史记录长度
        limit: 20,
        // 排除redux操作
        filter: excludeAction([
          `${C_PREFIX}resetComponent`,
          `${C_PREFIX}changeSelectedId`,
          `${C_PREFIX}selectPrevComponent`,
          `${C_PREFIX}selectNextComponent`,
        ]),
      }),
      pageInfo: pageInfoReducer,
    })
  ),
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware({
      // 关闭序列化状态检测中间件
      serializableCheck: false,
    });
  },
});

export const persistor = persistStore(store);
